package com.qcb.expresswrapping.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qcb.expresswrapping.common.Result;
import com.qcb.expresswrapping.entity.AddressInfo;
import com.qcb.expresswrapping.entity.LogisticsInfo;
import com.qcb.expresswrapping.entity.SendOrder;
import com.qcb.expresswrapping.entity.StationInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: QCB
 * @create: 2022-03-11-23:41
 * To change this template use File | Settings | File and Code Templates.
 */
@RestController
@RequestMapping("/mew/order")
public class MewOrderController extends BaseController{

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('mew:order:list')")
    public Result list(Integer status, Principal principal){
        List<SendOrder> sendOrders = scSendOrderService.list(new QueryWrapper<SendOrder>()
                .eq("posPhone", principal.getName())
                .eq(status!=null,"status", status).orderByDesc("createDate"));
        return Result.success(sendOrders);
    }

    @GetMapping("/info/{orderId}")
    @PreAuthorize("hasAnyAuthority('mew:order:info')")
    public Result info(@PathVariable("orderId") String orderId){
        SendOrder sendOrder = scSendOrderService.getById(orderId);
        List<LogisticsInfo> logisticsInfos = logisticsInfoService.listLogisiticsByOrderId(orderId);
        logisticsInfos.forEach(l ->{
            l.setCourier(pcUserInfoService.getById(l.getCourierId()));
        });
        sendOrder.setLogisticsInfos(logisticsInfos);
        return Result.success(sendOrder);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('mew:order:update')")
    public Result update(@Validated @RequestBody SendOrder sendOrder){
        sendOrder.setUpdateDate(new Date());
        scSendOrderService.updateById(sendOrder);
        return Result.success(sendOrder);
    }

    @GetMapping("/change/{orderId}/{status}")
    @PreAuthorize("hasAnyAuthority('mew:order:change')")
    public Result change(@PathVariable("orderId") String orderId, @PathVariable("status") Integer status){
        // 0：待处理    1：待投递   2：待收货   3：已签收   4：已取消   5：已退回
        SendOrder sendOrder = scSendOrderService.getById(orderId);
        sendOrder.setStatus(status);
        scSendOrderService.updateById(sendOrder);
        String msg = "";
        if (status == 1){
            msg = "包裹已入库！";
        }else if (status == 2){
            msg = "包裹已揽收！";
        }else if (status == 3){
            msg = "订单已签收！";
        }else if (status == 4){
            msg = "订单已取消！";
        }else if (status == 5){
            msg = "订单已退回！";
        }
        return Result.success(msg);
    }

    @GetMapping("/status/{status}")
    @PreAuthorize("hasAnyAuthority('mew:order:status')")
    public Result OrderStatus(@PathVariable("status") Integer status, Principal principal){
        List<SendOrder> orderStatus = scSendOrderService.list(new QueryWrapper<SendOrder>()
                .eq("porPhone", principal.getName())
                .eq("status", status)
                .orderByDesc("createDate")
        );
        return Result.success(orderStatus);
    }

    @GetMapping("/stationlist")
    @PreAuthorize("hasAnyAuthority('mew:order:stationlist')")
    public Result stationlist(){
        List<StationInfo> stationInfoList = scStationInfoService.list();
        return Result.success(stationInfoList);
    }

    @GetMapping("/myDefaultAddress")
    @PreAuthorize("hasAnyAuthority('pc:address:list')")
    public Result myDefaultAddress(Principal principal){
        AddressInfo addressInfo = pcAddressInfoService.getOne(new QueryWrapper<AddressInfo>()
        .eq("accountId", sysUserService.getByUsername(principal.getName()).getId())
        .eq("defaults", true));
        return Result.success(addressInfo);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('mew:order:save')")
    public Result save(@Validated @RequestBody SendOrder sendOrder, Principal principal){
        sendOrder.setOrderId("MTS" + new SimpleDateFormat("yyMMdd").format(new Date()) + (int)((Math.random()*9+1)*10000));
        sendOrder.setCreateDate(new Date());
        sendOrder.setUpdateDate(new Date());
        sendOrder.setStatus(0);
        scSendOrderService.save(sendOrder);
        return Result.success(sendOrder);
    }
}
